<template>
  <div id="xzqListTree" class="xzq-items">
    <el-select
      v-model="selectVal"
      placeholder="行政区列表"
      ref="select"
      style="width: 100%"
      :disabled="disabledInput"
      clearable
      @clear="clearSelectXzq"
    >
      <el-input
        class="input"
        placeholder="输入关键字进行过滤"
        prefix-icon="el-icon-search"
        v-model="treeFilter"
        size="mini"
        clearable
      ></el-input>
      <el-option hidden key="id" :value="selectVal" :label="selectName">
      </el-option>
      <el-tree
        :data="treeData"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
        :check-on-click-node="true"
        accordion
        ref="tree"
        node-key="code"
        :default-expand-all="false"
        :filter-node-method="filterNode"
      >
          <span slot-scope="{ data }">
          <span>{{ data.label }}</span>
        </span>
      </el-tree>
    </el-select>
  </div>
</template>

<script>

import Bus from '@/utils/bus'
import { getxzqList } from '@/api/gbznt/gbzCommon'
import { getMapRegionByCode } from '@/api/portal/regionConfig'
import globalmf from '@/utils/Global/GlobalMapFunction'

export default {
  name: 'XzqList',
  data() {
    return {
      optionData: {
        id: '',
        name: ''
      },
      disabledInput:false,
      xzqListTreeRender: null,
      config: {
        xzqLists: []
      },
      selectData: null,
      selectVal: '', // select框的绑定值
      selectName: '', // select框显示的name
      treeFilter: '', // 搜索框绑定值，用作过滤
      filterText: '',
      // 树形控件数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 标签数组
      tagList: [
        //  {value: "701", label: "宝泉岭"}
      ]
    }
  },
  props: {
    map: {
      type: Object
      // default() {
      //   return {}
      // }
    },
    mapRegion: {
      type: Object,
      default() {
        return {
          f_levels: 1,
          f_regioncode: 'f_regioncode',
          f_userid: -1,
          f_username: 'f_username',
          f_name: '',
          prjcode: 'EPSG:4490',
          userPrjCode: 'EPSG:4490',
          f_xmax: 140,
          f_xmin: 110,
          f_ymax: 53,
          f_ymin: 42,
          geomwkt: ''
        }
      }
    }
  },
  mounted() {
    this.queryXzqListAjax()
    //el的下拉框在css里改是没用的。就在这里改一下。
    this.$nextTick(() => {
      let selectDropDownNode = document.getElementsByClassName('el-select-dropdown__wrap')
      for (let i = 0; i < selectDropDownNode.length; i++) {
        selectDropDownNode[i].style.maxHeight = '450px'
      }
    })
    // Bus.$on('xzqListTreesetCurrentKey', msg => {
    //     this.handleNodeClick(msg);
    // });
  },
  beforeDestroy() {
    // Bus.$off('xzqListTreesetCurrentKey');
  },
  methods: {
    // 结构树点击事件
    handleNodeClick(currentData) {
      let that = this
      that.selectData = currentData
      that.selectData.orixzqCode = currentData.code
      if (currentData.level === 1) {//这个是为了查询用的，省级用户六位码直接截取2位
        that.selectData.xzqcode = currentData.code.substr(0, 2)
      } else if (currentData.level === 2) {//市级用户六位码直接截取4位
        that.selectData.xzqcode = currentData.code.substr(0, 4)
      } else {//县的level是3，直接用六位码。
        that.selectData.xzqcode = currentData.code
      }

      that.selectVal = currentData.value // select绑定值为点击的选项的value
      that.selectName = currentData.label // input中显示值为label
      that.treeFilter = '' // 点击后搜索框清空
      that.$refs.select.blur() // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠
      //这里需要执行以下统计里的代码，改了行政区后，统计里要修改统计的类型。
      Bus.$emit('proStatisChangeXZQ',[currentData])
      if (that.map != null) {
        //2022年04月10日 LQ ，选择对应分局或农场后，为了统计代码使用。
        Bus.$emit('selectedRegionsChangeBigStatistics', [currentData])
        var defaultPrjCode = that.mapRegion.prjcode
        var mapPrjCode = that.map.getView().getProjection().getCode()
        if (defaultPrjCode != mapPrjCode) {
          var leftBottom = ol.proj.transform([parseFloat(currentData.xmin), parseFloat(currentData.ymin)], defaultPrjCode, mapPrjCode)
          var rightTop = ol.proj.transform([parseFloat(currentData.xmax), parseFloat(currentData.ymax)], defaultPrjCode, mapPrjCode)
          that.map.getView().fit([leftBottom[0], leftBottom[1], rightTop[0], rightTop[1]])
        } else {
          that.map.getView().fit([parseFloat(currentData.xmin), parseFloat(currentData.ymin), parseFloat(currentData.xmax), parseFloat(currentData.ymax)])
        }
        if (currentData.level != '1') {
          that.loadRegionByCode(currentData.code)
        } else {
          var xzqLayer = globalmf.getLayerByName(that.map, 'xzqRegionLayer')
          if (xzqLayer != null) {
            xzqLayer.getSource().clear()
          }
        }
      }

    },
    // 模糊查询（搜索过滤），实质为筛选出树形控件中符合输入条件的选项，过滤掉其他选项
    filterNode(value, data) {
      if (!value) return true
      let filterRes = data.label.indexOf(value) !== -1
      return filterRes
    },
    // 选项卡标签（可忽略，增值迭代需求）
    filterorgType(val) {
      let arr = this.tagList.filter((item) => {
        return item.value == val
      })
      return arr.length ? arr[0].label : ''
    },
    loadRegionByCode(code) {
      let that = this;
      getMapRegionByCode(code).then((res) => {
        var regions = res.data.regions;
        if (regions != "") {
          var region = regions[0];
          var geomwkt = region.geomwkt;
          var xzqLayer = globalmf.getLayerByName(that.map, "xzqRegionLayer");
          if (xzqLayer == null) {
            xzqLayer = new ol.layer.Vector({
              name: "xzqRegionLayer",
              source: new ol.source.Vector({wrapX: false})
            });
            xzqLayer.setZIndex(9899);
            that.map.addLayer(xzqLayer);
          } else {
            xzqLayer.getSource().clear();
          }
          globalmf.addWKT2Layer(that.map, xzqLayer, geomwkt, null, {
            r: 255,
            g: 0,
            b: 0,
            a: 0
          }, true, that.mapRegion.prjcode);
          //增加遮罩
        }
      }).catch((error) => {
        // catch 指请求出错的处理
        console.log(error);
      });

    },
    queryXzqListAjax() {
      let that = this
      getxzqList().then(res => {
        let regions = res.rows
        if (regions != '') {
          that.treeData = []
          //that.setRegionsTreeData(null, regions);
          that.treeData = that.getXzqListData(regions, null)
        }
      })
    },

    data2treeDG(datas, dataArray) {
      for (let j = 0; j < dataArray.length; j++) {
        let dataArrayIndex = dataArray[j]
        let childrenArray = []
        let Id = dataArrayIndex.value
        for (let i = 0; i < datas.length; i++) {
          let data = datas[i]
          let pid = data.f_pcode
          if (pid == Id) {
            //判断是否为儿子节点
            let regionItem = {
              tag: data.f_code,
              label: data.f_name,
              value: data.f_code,
              selected: false,
              code: data.f_code,
              pcode: data.f_pcode,
              xmin: data.f_xmin,
              ymin: data.f_ymin,
              xmax: data.f_xmax,
              ymax: data.f_ymax,
              level: data.f_levels,
              children: []
            }
            //objTemp[pl] = data[pl]
            childrenArray.push(regionItem)
          }
        }
        dataArrayIndex.children = childrenArray
        if (childrenArray.length > 0) {
          //有儿子节点则递归
          this.data2treeDG(datas, childrenArray)
        }
      }
      return dataArray
    },
    getXzqListData(datas, bigPid) {
      let dataArray = []
      //datas.forEach(function(data) {
      for (let i = 0; i < datas.length; i++) {
        let data = datas[i]
        let pid = data.f_pcode
        if (pid == bigPid) {
          let regionItem = {
            label: data.f_name,
            value: data.f_code,
            selected: false,
            code: data.f_code,
            pcode: data.f_pcode,
            xmin: data.f_xmin,
            ymin: data.f_ymin,
            xmax: data.f_xmax,
            ymax: data.f_ymax,
            level: data.f_levels,
            children: []
          }
          dataArray.push(regionItem)
        }
      }
      //})
      return this.data2treeDG(datas, dataArray)
    },
    //清空已选择的
    clearSelectXzq() {
      this.selectVal = null
      this.selectName = null
      this.selectData = null
    },
    changeSelectName(name){
      this.selectName=name;
    },
  },
  watch: {
    // 搜索过滤，监听input搜索框绑定的treeFilter
    treeFilter(val) {
      this.$refs.tree.filter(val)
      // 当搜索框键入值改变时，将该值作为入参执行树形控件的过滤事件filterNode
    }
  }
}
</script>

<style scoped>
.xzq-items {
  width: 205px;
}

::v-deep .el-tree-node__expand-icon {
  font-size: 18px;
  color: #95b3f2;
  padding: 10px !important;
}


::v-deep .el-input__suffix {
  top: -5px;
}

::v-deep .el-popper {
  padding: 0 3px !important;
  margin-top: 1px !important;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #c8f5f9;
}

::v-deep .el-tree-node__content:hover {

  background-color: rgba(132, 235, 105, 0.48) !important;

}

::v-deep .el-input__inner {
  height: 30px;
  line-height: 30px;
}

::v-deep .el-input__icon {
  line-height: 30px;
}


.bd-ct-subwrap > div[type=xzqList] .layui-icon {
  color: #fff;
}
</style>
